﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Collections;

namespace freecart
{
    public static class ConnectionString { public static string String { get; set; } }

    public static class FreecartTheme { public static string Name { get; set; } }

    public static class CartManager
    {
        private static DataTable _carts = BuildTable();
        public static DataTable Carts { get { return _carts; } set { _carts = value; } }

        private static DataTable BuildTable()
        {
            DataTable dt = new DataTable();

            Dictionary<string, Type> dicColumns = new Dictionary<string, Type>();
                dicColumns.Add("ItemId", typeof(Guid));
                dicColumns.Add("SessionId", typeof(Guid));
                dicColumns.Add("Quantity", typeof(int));
                dicColumns.Add("Product", typeof(string));
                dicColumns.Add("UnitPrice", typeof(float));
                dicColumns.Add("Total", typeof(float));
                dicColumns.Add("Comment", typeof(string));

            foreach (KeyValuePair<string, Type> kvp in dicColumns)
                if (dt.Columns[kvp.Key] == null)
                {   // Adds the column only if it does not exist
                    dt.Columns.Add(kvp.Key, kvp.Value);
                }

            dt.AcceptChanges();

            return dt;
        }

        // ================================

        public static bool ClearCarts()
        {
            if (CartManager.Carts == null)
            {
                return false;
            }
            else
            {
                if (CartManager.Carts.Rows.Count >= 0)
                {
                    CartManager.Carts.Rows.Clear();
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }

    public class Freecart
    {
        private Guid _sessionId = Guid.Empty;
        public Guid SessionId { get { return _sessionId; } set { _sessionId = value; } }

        private string _theme = String.Empty;
        public string Theme { get { return _theme; } set { _theme = value; } }

        public Freecart()
        {
            // Constructor
        }

        public Freecart(string Connection_String) {
            ConnectionString.String = Connection_String;
        }
        
        // ================================

        public DataTable RetrieveCart()
        {
            DataTable dt = new DataTable();

            if (this.SessionId != Guid.Empty)
            {
                dt = RetrieveCart(this.SessionId);
            }
            else
            {
                throw new ArgumentException("Could not find a Session Id");
            }

            return dt;
        }

        public DataTable RetrieveCart(Guid SessionId)
        {
            DataTable dt = new DataTable();
            dt = CartManager.Carts;
            dt.DefaultView.RowFilter = "SessionId = '" + SessionId.ToString() + "'";
            //dt = FreecartTable.Table.
            return dt;
        }

        // ================================

        public static void RemoveSession(Guid SessionId)
        {
            var rows = CartManager.Carts.Select("SessionId = '" + SessionId.ToString() + "'");
            foreach (var row in rows)
            {
                row.Delete();
            }

            CartManager.Carts.AcceptChanges();
        }

        // ================================

        public bool UpdateQuantity(string ItemId, string Quantity)
        {
            if (this.SessionId == Guid.Empty)
                throw new ArgumentException("Could not find a Session Id");
            else
            {
                return UpdateQuantity(this.SessionId, ItemId, Quantity);
            }
        }

        public bool UpdateQuantity(Guid SessionId, string ItemId, string Quantity)
        {
            if (String.IsNullOrEmpty(ItemId) && CartManager.Carts == null)
            {
                throw new ArgumentException("Could not find data table, item id, or quantity.");
            } 
            else {
                DataRow[] rows = CartManager.Carts.Select("ItemId = '" + ItemId + "' AND SessionId = '" + SessionId.ToString() + "'");
                if (rows.Length >= 0)
                {
                    foreach (DataRow row in rows)
                    {
                        row["Quantity"] = Quantity.ToString();
                    }

                    CartManager.Carts.AcceptChanges();
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        // ================================

        public bool RemoveItemFromCart(string ItemId)
        {
            if (this.SessionId == Guid.Empty)
            {
                throw new ArgumentException("Session Id is empty.");
            }
            else
            {
                return RemoveItemFromCart(this.SessionId, ItemId);
            }
        }
        
        public bool RemoveItemFromCart(Guid SessionId, string ItemId)
        {
            if (CartManager.Carts != null)
            {
                if (!String.IsNullOrEmpty(ItemId))
                {
                    var rows = CartManager.Carts.Select("ItemId = '" + ItemId + "' AND SessionId = '" + SessionId.ToString() + "'");

                    if (rows.Length > 0)
                    {
                        foreach (var row in rows)
                        {
                            row.Delete();
                        }
                        CartManager.Carts.AcceptChanges();
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                    throw new ArgumentException("Missing DataTable or Item Id.");
            }
            else
            {
                throw new ArgumentException("Missing Datatable not created.");
            }
        }

        // ================================

        public bool AddItemToCart(string SerializedForm)
        {
            if (this.SessionId == Guid.Empty)
                throw new ArgumentException("Session Id is empty.");
            else
                return AddItemToCart(this.SessionId.ToString(), SerializedForm);
        }

        public bool AddItemToCart(string SessionId, string SerializedForm)
        {
            if (!String.IsNullOrEmpty(SessionId) && !String.IsNullOrEmpty(this.SessionId.ToString()))
            {
                if (CartManager.Carts != null)
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    // serializer.Deserialize

                    for (int i = 0; i <= CartManager.Carts.Columns.Count; i++)
                    {
                        // break;
                    }

                    CartManager.Carts.AcceptChanges();
                    return true;
                }
                return false;
            }
            else
            {
                throw new ArgumentException("Session Id is empty.");
            }
        }

        // ================================

        public void SampleTable()
        {
            if (this.SessionId == Guid.Empty)
                throw new ArgumentException("Session Id is empty.");
            else 
                SampleTable(this.SessionId);
        }

        public void SampleTable(Guid SessionId)
        {
            if (CartManager.Carts.Columns.Count > 0)
            {
                DataRow dr;
                for (int i = 0; i < 10; i++)
                {
                    dr = CartManager.Carts.NewRow();
                    dr["ItemId"] = System.Guid.NewGuid();
                    dr["SessionId"] = SessionId;
                    dr["Product"] = "Product" + i + " Name";
                    dr["Quantity"] = 3 + i;
                    dr["UnitPrice"] = 3.41;
                    CartManager.Carts.Rows.Add(dr);
                }

                CartManager.Carts.AcceptChanges();
            }
        }

        // ================================

        public void RetrieveItem(string ItemId)
        {
            // TODO:
            // should return just raw html
            // do not pass back xml or json to the browser
            //
        }
    }
}
